
package org.avro;

import java.io.File;
import java.io.IOException;

import org.apache.avro.Schema;
import org.apache.avro.Schema.Parser;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 基于Schema的序列化方式
 * 
 * @author donald 2018年3月11日 下午6:53:10
 */
public class GenericMain {
	private static final Logger log = LoggerFactory.getLogger(GenericMain.class);

	@SuppressWarnings("resource")
	public static void main(String[] args) throws IOException {
		Schema schema = new Parser().parse(new File("F:/gitee/serializable-demo/src/main/resources/avro/user.avsc"));

		GenericRecord user1 = new GenericData.Record(schema);
		user1.put("name", "donald");
		user1.put("age", 256);
		// Leave emailr null

		GenericRecord user2 = new GenericData.Record(schema);
		user2.put("name", "Rain");
		user2.put("age", 7);
		user2.put("email", "shaoqinghan@gmai.com");
		log.info("start Serialize user1 and user2 to disk");
		// Serialize user1 and user2 to disk
		File file = new File("users.avro");
		DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
		DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
		dataFileWriter.create(schema, file);
		dataFileWriter.append(user1);
		dataFileWriter.append(user2);
		dataFileWriter.close();
		log.info("ended Serialize user1 and user2 to disk");
		log.info("Deserialize users from disk");
		
		// Deserialize users from disk
		DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(schema);
		DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader);
		GenericRecord user = null;
		while (dataFileReader.hasNext()) {
			// Reuse user object by passing it to next(). This saves us from
			// allocating and garbage collecting many objects for files with
			// many items.
			user = dataFileReader.next(user);
			log.info("Deserialize users info:{}",user);
		}
		
	}
}
